package com.thingple.reader;

import android.annotation.SuppressLint;
import android.hardware.usb.UsbAccessory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.thingple.usb.LimitedClick;
import com.thingple.usb.manager.UsbManagerWrapper;
import com.thingple.util.Alert;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ReaderActivity extends AppCompatActivity {

    private static final String TAG = ReaderActivity.class.getName();

    private UsbReader reader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_reader);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        Alert.ctx = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        init();
    }

    private void init() {
        initUI();

        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Log.d(TAG, "init Usb device");
            initReader();
        }, 500);

    }

    private void initReader() {
        reader = new UsbReader(this, (session, err) -> {
            // TODO
            if (err != null) {
                return;
            }

            UsbAccessory device = session.getDevice();
            String name = String.format("%s\n[%s:%s]",
                    device.getSerial(),
                    device.getManufacturer(),
                    device.getModel());
            refreshLog("设备名:" + name);

            Alert.msg("设置Log监听器");

            session.setErrorListener((e) -> {
                Log.d(TAG, "usb通信中断");
                usbLostTimes++;
//            refreshStatus("usb通信中断:" + usbLostTimes + "次 " + e.getMessage());
                refreshLog("usb通信中断:" + usbLostTimes + "次 " + e.getMessage());
            });
            session.setStreamDownListener((data, n, async) -> {
                Log.d(TAG, "自定义处理器:");
//                    String log = Strings.hexFmt(data).toUpperCase();
            });
            session.setTraceListener(content -> {
                Log.d(TAG, "trace:" + content);
                refreshLog(content);
            });
        });
        reader.setTagListener(tagInfo -> {
            Log.d(TAG, "-->tag:" + tagInfo.epc);
            if (tagInfo.epc.startsWith("03")) {
                refreshAction("托盘", tagInfo.epc);
            } else if (tagInfo.epc.startsWith("04")) {
                refreshAction("库位", tagInfo.epc);
            } else if (tagInfo.epc.startsWith("05")) {
                refreshAction("站台", tagInfo.epc);
            } else {
                refreshAction("未知", tagInfo.epc);
            }
        }).setCarryStateListener(state -> {
            String m = state == 1?"有货":"无货";
            refreshAction("货物状态", m);
        }).connect();
    }

    private void initUI() {
        Button btnLog = findViewById(com.thingple.usb.R.id.btn_log);
        btnLog.setOnClickListener(new LimitedClick(300, v -> logViewControl(btnLog)));
        TextView statusLabel = findViewById(com.thingple.usb.R.id.txt_status);
        statusLabel.setVisibility(View.INVISIBLE);
    }

    private boolean showLogView = false;

    private void logViewControl(Button btn) {
        showLogView = !showLogView;
        View sv = findViewById(com.thingple.usb.R.id.sv);
        View log = findViewById(com.thingple.usb.R.id.scr_log);
        if (showLogView) {
            btn.setText("关闭日志");
            sv.setVisibility(View.INVISIBLE);
            log.setVisibility(View.VISIBLE);
        } else {
            btn.setText("显示日志");
            sv.setVisibility(View.VISIBLE);
            log.setVisibility(View.INVISIBLE);
        }
    }

    int usbLostTimes = 0;

    int lines = 0;
    @SuppressLint("SetTextI18n")
    private void refreshAction(String action, String payload) {
        lines = lines%23;
        lines++;

        Date now = Calendar.getInstance().getTime();
        @SuppressLint("DefaultLocale")
        final String content = String.format("[%s]: (%s)%s\r\n", fmt(now), action, payload);
        new Handler(Looper.getMainLooper()).post(() -> {

            ScrollView scrollView = findViewById(com.thingple.usb.R.id.sv);
            TextView textLog = findViewById(com.thingple.usb.R.id.txt_rx);

            if (lines == 1) {
                textLog.setText(content);
            } else {
                textLog.append(content);
            }

            scrollView.post(() -> {
                // TODO
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            });
        });
    }

    int logLines = 0;
    @SuppressLint("SetTextI18n")
    private void refreshLog(String payload) {

        @SuppressLint("DefaultLocale")
        final String content = String.format("%d:%s\r\n", logLines, payload);
        new Handler(Looper.getMainLooper()).post(() -> {
            logLines = logLines%23;
            logLines++;
            ScrollView scrollView = findViewById(com.thingple.usb.R.id.scr_log);
            TextView textLog = findViewById(com.thingple.usb.R.id.txt_log);

            if (logLines == 1) {
                textLog.setText(content);
            } else {
                textLog.append(content);
            }

            scrollView.post(() -> {
                // TODO
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            });
        });
    }

    DateFormat df;

    @SuppressLint("SimpleDateFormat")
    private String fmt(Date date) {
        if (df == null) {
            df = new SimpleDateFormat("HH:mm:ss");
        }
        return df.format(date);
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "Reader Activity destroy");

        // 先清理资源
        if (reader != null) {
            reader.close();
            reader = null;
        }

        // 再销毁自己
        super.onDestroy();
    }
}